
#include <GL/glew.h>
#include <GL/glut.h>
#include "../../Header/misc/cSkyBox.h"
#include "../../Header/misc/nvMath.h"
#include "../../Header/Camera.h"
#include "../../Header/misc.h"
#include "../../Header/ShaderObject.h"

cSkyBox::cSkyBox(char *fileName)
{
	
	nv::Image img;
	if (!img.loadImageFromFile(fileName))
	{
		fprintf(stderr, "Error loading image file '%s'\n",fileName);
		return;
	};
	
	if (!img.convertCrossToCubemap()) {
		fprintf(stderr, "Error converting image to cubemap\n");
        return;        
	};
	
	texId = createCubemapTexture(img, GL_RGBA16F_ARB);

}

cSkyBox::~cSkyBox()
{
}

unsigned int cSkyBox::createCubemapTexture(nv::Image &img, unsigned int internalformat)
{
    GLuint tex; 
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_CUBE_MAP, tex);

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2.0);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);

    // load face data
    for(int i=0; i<6; i++) {
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
                     internalformat, img.getWidth(), img.getHeight(), 0, 
                     GL_RGB, GL_FLOAT, img.getLevel(0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i));
    }

    return tex;
}

void cSkyBox::draw(Camera *cam, ShaderObject *shader)
{

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, texId);
    //glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.0f);

	glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
	
	glPushMatrix();
    glLoadIdentity();

	gluLookAt(
		0,0,0,
        cam->dir[0], cam->dir[1], cam->dir[2],
        0,1,0);
	
	shader->activate();
		glutSolidCube(1.0);
	shader->deactivate();
    glPopMatrix();
    glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

}


